﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BuildingTomorow
{
    public class Rule
    {
        public String Name { get; set; }
        public String Description { get; set; }
        public TimeSpan EvaluateTime { get; set; }
        public bool Status { get; set; }
        public List<Action> PositiveActions { get; set; }
        public List<Action> Negativections { get; set; }
        public List<Condition> Conditions { get; set; }
        public List<Operator> Operators { get; set; }


        public Rule()
        {
            PositiveActions = new List<Action>();
            Negativections = new List<Action>();
            Conditions = new List<Condition>();
            Operators = new List<Operator>();
            Operators.Add(new Operator() { Op = "||" });
        }

        public void Run()
        {
            if (Evaluate())
            {
                foreach (var action in PositiveActions)
                {
                    action.Execute();
                }
            }
            else
            {
                foreach (var action in Negativections)
                {
                    action.Execute();
                }
            }
        }
        private bool Evaluate()
        {
            bool firstBool = false;
            for (int i = 0; i < Conditions.Count; i++)
            {
                firstBool = ConbinedEvaluation(firstBool,Operators.ElementAt(i),Conditions.ElementAt(i));
            }
            return firstBool;
        }
        private bool ConbinedEvaluation(Condition con1, Operator op, Condition con2)
        {
            switch (op.Op)
            {
                case "&&":
                    return con1.IsConditionMet() && con2.IsConditionMet();
                case "||":
                    return con1.IsConditionMet() || con2.IsConditionMet();
                default:
                    return false;
            }
        }
        private bool ConbinedEvaluation(bool con1, Operator op, Condition con2)
        {
            switch (op.Op)
            {
                case "&&":
                    return con1 && con2.IsConditionMet();
                case "||":
                    return con1 || con2.IsConditionMet();
                default:
                    return false;
            }
        }
    }
}
